package edu.cicese.alz.swing;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import java.awt.Dialog.ModalityType;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BlinkingFrame {
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame();

				JButton button = new JButton("Show blinking frame");
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						showBlinkingFrame((JButton) e.getSource(), "Emergency!");
					}
				});

				frame.setLayout(new java.awt.GridBagLayout());
				frame.add(button);

				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		});
	}

	public static void showBlinkingFrame(java.awt.Component owner, String message) {
		//invisible frame that takes the focus away from the popup
		final JDialog phantomFrame = new JDialog();
		phantomFrame.setModal(false);
		phantomFrame.setUndecorated(true);
		phantomFrame.setVisible(true);

		//the dialog popup
		JOptionPane optionPane = new JOptionPane(message,
				JOptionPane.WARNING_MESSAGE);
		final JDialog popup = optionPane.createDialog(owner, "Blinking Frame");

		//we need the dialog to be Document Modal so the invisible frame can
		//take away the focus
		popup.setModalityType(ModalityType.DOCUMENT_MODAL);

		//blinker
		Timer blinker = new Timer(1000, new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!popup.isDisplayable()) {
					((Timer) e.getSource()).stop();
				} else {
					phantomFrame.requestFocus();
					Toolkit.getDefaultToolkit().beep();
					popup.requestFocus();
				}
			}
		});
		blinker.setInitialDelay(300);
		blinker.start();

		popup.setVisible(true);

		//cleanup
		popup.dispose();
		phantomFrame.dispose();
	}
}